package com.scale;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.ruoyi.RuoYiApplication;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.json.JsonUtils;
import com.ruoyi.scale.document.Scale;
import com.ruoyi.scale.document.refs.*;
import com.ruoyi.scale.model.GrowthNormDataWrap;
import com.ruoyi.scale.service.ScaleService;
import org.bson.Document;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Example;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@RunWith(SpringRunner.class)
@SpringBootTest(classes = RuoYiApplication.class)
public class ImportScale {

    @Resource
    private ScaleService scaleService;

    @Before
    public void before(){
//        Scale<GrowthNormDataWrap> queryWhere = new Scale<>();
//        queryWhere.setRuleName("growthEvalRule");
//
//        List<Scale> scales = scaleService.findAll(Example.of(queryWhere));
//        for (Scale scale : scales) {
//            scaleService.delete(scale);
//        }
    }
    public void delete(String code){
        if(scaleService == null){
            return;
        }
        Scale queryWhere = new Scale();
        queryWhere.setCode(code);
        List<Scale> scales = scaleService.findAll(Example.of(queryWhere));
        for (Scale scale : scales) {
            scaleService.delete(scale);
        }
    }

    public static void main(String[] args) {
       // new ImportScale().singleImport(new File("F:\\富格伦项目\\江西人民医院\\江西量表数据\\艾森克个性测验EPQ.txt"));
      //  System.out.println(StringUtils.replace(PinyinUtil.getPinyin("艾森克个性测验EPQ")," ","_"));

        new ImportScale().singleImport(new File("F:\\富格伦项目\\江西人民医院\\江西量表数据\\SCL-90.txt"));
    }

    @Test
    public void startImport() throws IOException {

//        Files.list(Paths.get("F:\\富格伦项目\\江西人民医院\\江西量表数据")).forEach(t -> {
//            try {
//                singleImport(t.toFile());
//            }catch (Exception e){
//                e.printStackTrace();
//                System.err.println("解析:" + t.toFile().getAbsoluteFile() + "  出错!");
//            }
//        });
        singleImport(new File("F:\\富格伦项目\\江西人民医院\\江西量表数据\\SCL-90.txt"));
        //singleImport(new File("F:\\富格伦项目\\江西人民医院\\江西量表数据\\艾森克个性测验EPQ.txt"));
        //singleImport(new File("F:\\富格伦项目\\江西人民医院\\江西量表数据\\7项广泛性焦虑障碍量表GAD-7.txt"));
    }

    public String getCode(String code){
        code= StringUtils.replace(code,".txt","");
        return StringUtils.replace(PinyinUtil.getPinyin(code)," ","_");
    }
    public void singleImport(File file){
        String code = getCode(file.getName());
        this.delete(code);
        Document doc = Document.parse(FileUtil.readString(file, Charset.forName("GB2312")));
        Scale scale = new Scale();
        scale.setName(doc.get("name",String.class));
        scale.setCode(code);
        scale.setRuleName("commonEvalRule");
        //
        scale.setCategoryId(1l);
        scale.setDetailDesc(doc.get("remarks",String.class));
        scale.setDelFlag(0);
        //scale.setId();
        scale.setPriority(1);
        scale.setReportShowComponent("gaugeResult");

        List qlist = doc.get("items", List.class);

        List<ScaleQuestion> items = new ArrayList<>();
        for (int j = 0; j < qlist.size(); j++) {
            Document document = (Document)qlist.get(j);
            ScaleQuestion scaleQuestion = new ScaleQuestion();
            scaleQuestion.setNo(j + 1);
            // scaleQuestion.setDesc(document.get("text",String.class));
            scaleQuestion.setName(document.get("text",String.class));
            scaleQuestion.setType("radio");
            List<Document> values = (List<Document>)document.get("values");

            List<ScaleAnswerEntry> answers = new ArrayList<>();
            for (int i = 0; i < values.size(); i++) {
                Document w = values.get(i);
                ScaleAnswerEntry entry = new ScaleAnswerEntry();
                entry.setDesc(null);
                entry.setNo(scaleQuestion.getNo());
                entry.setKey(w.get("text",String.class));
                entry.setText(w.get("text",String.class));
                Object score = w.get("score");
                BigDecimal bdValue = getBdValue(score);
                entry.setScore(bdValue);
                entry.setVal(bdValue);
                answers.add(entry);
            }
            scaleQuestion.setAnswers(answers);
            items.add(scaleQuestion);
        }


        scale.setQuestions(items);

        //总分评估规则
        List<Document> evaluations = doc.get("evaluations", List.class);
//        NormData rules = new NormData();


        List<ScaleDomainRule> collect = evaluations.stream().map(t -> {
            Document d = (Document) t;
            ScaleDomainRule rule = new ScaleDomainRule();

            rule.setMax(getBdValue(d.get("max")));
            rule.setMin(getBdValue(d.get("min")));
//            rule.setAdvice(d.getString("advice"));
            rule.setAdvice(d.getString("shortAdvice"));
            rule.setConclusion(d.getString("text"));
            rule.setDetailAdvice(d.getString("desc"));
           // rule.setText(d.getString("text"));
            return rule;
        }).collect(Collectors.toList());


        scale.setTotalScoreRule(collect);

        //阶段评估规则
        List<Document> pluginConfigs = doc.get("pluginConfigs", List.class);
        if(!CollectionUtils.isEmpty(pluginConfigs)){
            // scaleStageData.setScaleStageRules(collect);
            String multiItemPlugin = pluginConfigs.get(0).get("data", String.class);

            List<Map<String, Object>> dataList = JsonUtils.deserialize(multiItemPlugin, new TypeReference<List<Map<String, Object>>>() {
            });
            List<ScaleDomainData> scaleDomainDataList = new ArrayList<>();
            for (Map<String, Object> map : dataList) {
                Object name = map.get("name");
                List<Map<String,Object>> ranges = (List<Map<String,Object>>)map.get("ranges");

                ScaleDomainData scaleDomainData = new ScaleDomainData();
                scaleDomainData.setName(name.toString());
                scaleDomainData.setDesc(map.getOrDefault("desc","").toString());
                scaleDomainData.setScaleDomainRules(new ArrayList<>());
                scaleDomainData.setQuestionNos(new ArrayList<>());
                //题号
                for (Map<String, Object> range : ranges) {
                    Integer start = Integer.valueOf(range.get("start").toString());
                    Integer end = Integer.valueOf(range.get("end").toString());

                    for (int i = start+1; i <= end; i++) {
                        scaleDomainData.getQuestionNos().add(i);
                    }
                }
                //规则
                List<Map<String,Object>> evaluations1 =(  List<Map<String,Object>>) map.get("evaluations");
                for (Map<String, Object> stringObjectMap : evaluations1) {
                    String min = stringObjectMap.get("min").toString();
                    String max = stringObjectMap.get("max").toString();
                    String text = stringObjectMap.getOrDefault("text","").toString();
                    String desc = stringObjectMap.getOrDefault("desc","").toString();
                    ScaleDomainRule scaleDomainRule = new ScaleDomainRule();
                    scaleDomainRule.setAdvice(desc);
                    scaleDomainRule.setConclusion(text);
//                    scaleStageRule.setDetailAdvice();
                    scaleDomainRule.setMax(new BigDecimal(max));
                    scaleDomainRule.setMin(new BigDecimal(min));
                    scaleDomainData.getScaleDomainRules().add(scaleDomainRule);
                }
                scaleDomainDataList.add(scaleDomainData);
            }
            scale.setScaleDomainData(scaleDomainDataList);
        }




//        scale.setNormData(rules);
        System.out.println(file.getName() + ":" + JSON.toJSONString(scale));
        this.scaleService.save(scale);
    }
    private static BigDecimal getBdValue(Object score) {
        if(score == null){
            return null;
        }
        if(score instanceof Integer){
            return BigDecimal.valueOf((Integer) score);
        } else if(score instanceof Double){
            return BigDecimal.valueOf((Double) score);
        } else {
            throw new IllegalArgumentException("不支持的数据类型:" + score.getClass());
        }
    }
}
